﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using Twc.Deployment.Client.Logic.Commands;
using System.Threading;

namespace Twc.Deployment.Client.Logic.DeploymentActions
{
    public class SPBackupDeployAction : BaseDeployAction
    {


        public SPBackupDeployAction(DeployService deployService)
            : base(deployService)
        {

        }

        public override DeploymentResult Deploy()
        {
            var spBackupFile = getSPBackupFile();
            var deploymentResult = new DeploymentResult();

            using (var processService = new ProcessService())
            {


                CommandGenerator = new STSADMCommandGenerator();
                (CommandGenerator as STSADMCommandGenerator).Operation = Operation.RESTORE;
                (CommandGenerator as STSADMCommandGenerator).Url = this.DeployService.SiteCollection.Url;
                (CommandGenerator as STSADMCommandGenerator).FileName = spBackupFile.FullName;
                (CommandGenerator as STSADMCommandGenerator).Overwrite = true;

                processService.WriteCommand("C:");

                processService.WriteCommand("cd " + SP12HIVE + @"\BIN");
                //processService.WriteCommandAndWait(CommandGenerator.GenerateCommand(), 6000);
                processService.WriteCommand(CommandGenerator.GenerateCommand());
                processService.WriteExitCommand();

                deploymentResult.CommandInput += CommandGenerator.GenerateCommand() + Environment.NewLine;
                deploymentResult.CommandOutput += processService.ReadOutput() + Environment.NewLine;
            }
            return deploymentResult;
        }

        private FileInfo getSPBackupFile()
        {
            return new FileInfo(this.GetType().Assembly.Location).Directory.GetFiles("*.bak").FirstOrDefault();
        }

        public override DeploymentResult Undeploy()
        {
            var deploymentResult = new DeploymentResult() {  CommandInput="No undeploy action for SPBackup"};
            return deploymentResult;
        }

    }
}
